<template>
  <div>
    <!-- 顶部操作栏 -->
    <div class="header-container">
      <span class="title">商品添加</span>
    </div>

    <!-- 商品添加表单 -->
    <el-form
      :model="addForm"
      label-width="120px"
      style="max-width: 600px; margin-top: 20px"
    >
      <el-form-item label="商品名称">
        <el-input
          v-model="addForm.name"
          placeholder="请输入商品名称"
        />
      </el-form-item>

      <el-form-item label="商品分类">
        <el-select
          v-model="addForm.category"
          placeholder="请选择商品分类"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.cateName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品价格">
        <el-input-number
          v-model="addForm.price"
          :min="0"
          :step="0.1"
        />
      </el-form-item>

      <el-form-item label="商品图片">
        <div class="image-upload-container">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <!-- 如果有图片，显示图片预览 -->
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <!-- 如果没有图片，显示加号图标 -->
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="商品描述">
        <el-input
          v-model="addForm.goodsDesc"
          type="textarea"
          placeholder="请输入商品描述"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">添加商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { catelist, goods_img_upload, add } from '@/views/api/goods.js';
import { Plus } from '@element-plus/icons-vue';

const addForm = reactive({
  name: '',
  category: '',
  price: 0,
  imgUrl: '',
  goodsDesc: ''
});

const imageUrl = ref('');
const categoryOptions = ref([]);
const uploadUrl = ref(import.meta.env.VITE_API_BASE_URL ? `${import.meta.env.VITE_API_BASE_URL}/goods/goods_img_upload` : '/api/goods/goods_img_upload');

// 获取商品分类列表
const getCategoryList = async () => {
  try {
    const res = await catelist({
      currentPage: 1,
      pageSize: 100
    });
    if (res.total !== undefined && res.data !== undefined) {
      categoryOptions.value = res.data.map(item => ({
        id: item.id,
        cateName: item.cateName
      }));
    } else {
      throw new Error('后端返回的数据结构不符合预期');
    }
  } catch (error) {
    ElMessage.error(`获取商品分类列表失败：${error.message}`);
    console.error('获取商品分类列表失败详情：', error);
  }
};

// 处理图片上传成功
const handleUploadSuccess = (response, file) => {
  if (response.code === 0) {
    ElMessage.success('图片上传成功');
    addForm.imgUrl = response.imgUrl;
    imageUrl.value = URL.createObjectURL(file.raw);
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};

// 上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt500K = file.size / 1024 < 500;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt500K) {
    ElMessage.error('上传图片大小不能超过 500KB!');
    return false;
  }
  return true;
};

// 提交商品添加表单
const handleSubmit = async () => {
  if (!addForm.name) {
    ElMessage.warning('商品名称不能为空');
    return;
  }
  if (!addForm.category) {
    ElMessage.warning('商品分类不能为空');
    return;
  }
  if (!addForm.imgUrl) {
    ElMessage.warning('商品图片不能为空');
    return;
  }
  if (!addForm.goodsDesc) {
    ElMessage.warning('商品描述不能为空');
    return;
  }

  try {
    const res = await add(addForm);
    if (res.code === 0) {
      ElMessage.success('商品添加成功');
      // 重置表单
      Object.assign(addForm, {
        name: '',
        category: '',
        price: 0,
        imgUrl: '',
        goodsDesc: ''
      });
      imageUrl.value = '';
    } else {
      ElMessage.error(res.msg || '商品添加失败');
    }
  } catch (error) {
    ElMessage.error('商品添加失败');
  }
};

onMounted(() => {
  getCategoryList();
});
</script>

<style scoped>
.header-container {
  padding: 20px;
  border-bottom: 2px solid #ccc;
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-right: auto;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
  height: 178px;
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>